#include <iostream>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <thread>

class Foo {//使用条件变量
private:
    std::mutex mtx;                   // 互斥量，用于保护 state 变量
    std::condition_variable cv;       // 条件变量，用于线程同步
    int state;                        // 状态变量，跟踪执行的进度

public:
    Foo() : state(0) {}               // 构造函数初始化 state 为 0

    void first(std::function<void()> printFirst) {
        std::unique_lock<std::mutex> lock(mtx);  // 上锁
       
        printFirst();

        state = 1;

        // 通知所有等待的线程
        cv.notify_all();
    }

    void second(std::function<void()> printSecond) {
        std::unique_lock<std::mutex> lock(mtx); 
       
        cv.wait(lock, [this] { return state == 1; }); 

        printSecond(); 

        state = 2;
        cv.notify_all();
    }

    void third(std::function<void()> printThird) {
        std::unique_lock<std::mutex> lock(mtx);  
        cv.wait(lock, [this] { return state == 2; });

        printThird();
    }
};

void callFirst(Foo& foo) {
    foo.first([]{ std::cout << "first\n"; });
}

void callSecond(Foo& foo) {
    foo.second([]{ std::cout << "second\n"; });
}


class FooCaller {
public:
    static void callThird(Foo& foo) {
        foo.third([]{ std::cout << "third\n"; });
    }
};

int main() {
    Foo foo;  // 创建 Foo 类实例

    // 创建并启动三个线程，分别调用 first, second, third 方法
    //三种创建线程的方法
    std::thread t1(std::bind(callFirst, std::ref(foo)));
    std::thread t2([&foo] { callSecond(foo); });
    std::thread t3(std::bind(&FooCaller::callThird, std::ref(foo)));
 
   
    // 等待三个线程完成
    t1.join();
    t2.join();
    t3.join();

    return 0;
}